<?php

namespace inhere\simditor;

use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

/**
 * simditor Widget
 * simditor editer @link https://github.com/mycolorway/simditor
 */
class Simditor extends \yii\widgets\InputWidget
{
    /**
     * @var array
     * 请注意下面选项的数据类型 [use json_encode()]    
     */
    private $defautOptions = [
        'textarea'    => '', 
        'placeholder' => 'place input content ....',

        /*
        toolbar Boolean|Array default: true
        Show toolbar buttons. Accpect an array of buttons that includes：
        ['title', 'bold', 'italic', 'underline', 'strikethrough', 'color', 'blockquote', 
          'code', 'table', 'link', 'image', 'hr', 'indent', 'outdent', 'alignment']
         */
        'toolbar'            => true,
        'toolbarFloat'       => true,
        'toolbarFloatOffset' => 0,
        'toolbarHidden'      => false,
        'defaultImage'       => '/images/image.png',
        'tabIndent'          => true, // Use 'tab' key to make an indent.
        'params'             => [],

        'upload'    => false, 

        'pasteImage' => false,

        /* 
        Array/String default: ['upload', 'external']
        Insert images by uploading from the local computer or external links. If both are enabled, 
        Simditor will show a drop-down menu when click the image button.
        */
        'imageButton' => ['upload', 'external'],

        // allowedTags Array default: null
        // Tags that are allowed in Simditor. Default whitelist:
        // 'allowedTags' => null,

        /*
        allowedAttributes Array default: null
        Whitelist of tag attributes. style attribute whitelist is defined in allowedStyles. Default whitelist:
        [
            img: ['src', 'alt', 'width', 'height', 'data-non-image']
            a: ['href', 'target']
            font: ['color']
            code: ['class']
        ]
        */
        'allowedAttributes' => null,

        /*
        allowedStyles Array default: null
        Inline style whitelist. Default whitelist:
        [
            p: ['margin-left', 'text-align']
            h1: ['margin-left']
            h2: ['margin-left']
            h3: ['margin-left']
            h4: ['margin-left']
        ]
        */
        'allowedStyles' => null,

        /*
        codeLanguages Array default: null
        A list of programming languages supported by code block. Default list:
        [
          { name: 'Bash', value: 'bash' }
          { name: 'C++', value: 'c++' }
          { name: 'C#', value: 'cs' }
          { name: 'CSS', value: 'css' }
          { name: 'Erlang', value: 'erlang' }
          { name: 'Less', value: 'less' }
          { name: 'Sass', value: 'sass' }
          { name: 'Diff', value: 'diff' }
          { name: 'CoffeeScript', value: 'coffeescript' }
          { name: 'HTML,XML', value: 'html' }
          { name: 'JSON', value: 'json' }
          { name: 'Java', value: 'java' }
          { name: 'JavaScript', value: 'js' }
          { name: 'Markdown', value: 'markdown' }
          { name: 'Objective C', value: 'oc' }
          { name: 'PHP', value: 'php' }
          { name: 'Perl', value: 'parl' }
          { name: 'Python', value: 'python' }
          { name: 'Ruby', value: 'ruby' }
          { name: 'SQL', value: 'sql'}
        ]
        */
       'codeLanguages' => null,
    ];

    /**
     * 默认上传设置，这里单独设置置
     * JSON response after uploading complete:
     * {
     *    "success": true/false,
     *    "msg": "error message", # optional
     *    "file_path": "[real file path]"
     * }
     * @var array
     */
    private $defaultUploadOptions = [
        'url'             => '',  // upload url
        'params'          => null,  // [ 'key' => 'value'] extra params sent to the server;
        'fileKey'         => 'upload_file', //  key of the file param;
        'connectionCount' => 3,  //  how many images can be uploaded simultaneously;
        'leaveConfirm'    => 'Uploading is in progress, are you sure to leave this page?',         
    ];

    private $defaultToolbar = [
        'title', 'bold', 'italic', 'underline', 'strikethrough', 'color', 'blockquote', 
        'code', 'table', 'link', 'image', 'hr', 'indent', 'outdent', 'alignment'
    ];

    /**
     *  编辑器选项设置, 将会与上面的默认配置合并
     * @var array
     */
    public $editorOptions = [];

    /**
     * 启用相关扩展 -- 得下载了相关扩展 并在 SimditorAsset 配置了相关文件加载才行
     * enable simditor extension
     * @see SimditorAsset::$extendOptions
     * @var array
     */
    public $enableExtend = [
        // 'html',
        // 'fullscreen',
        'markdown',
    ];

    public function run()
    {
        $extends = SimditorAsset::enableExtend($this->enableExtend);
        SimditorAsset::register($this->getView());

        $jsonOption = $this->handleOptions($extends);

        $this->getView()->registerJs("
    var config = $jsonOption;
    var editor = new Simditor(config);
    ");

        if ($this->hasModel()) {
            return Html::activeTextarea($this->model, $this->attribute, $this->options);
        } else {
            return Html::textarea($this->name, $this->value, $this->options);
        }
    }

    /**
     * 处理选项设置
     * @return array|string -- json
     */
    protected function handleOptions($extends)
    {
        $options = array_merge($this->defautOptions, $this->editorOptions);

        // code...
        if ( $extends ) {
            if (!is_array($options['toolbar'])) {
                $options['toolbar'] = $this->defaultToolbar;
            }

            $options['toolbar'][] = '|';
        }
        foreach ($extends as $name => $value) {
            if ( !in_array($name, $options['toolbar'])) {
                $options['toolbar'][] = $name;
            }
        }

        if (isset($options['textarea']) && strpos($options['textarea'],'$') !== false) {
            $textarea = '"textarea":$("'.$options['textarea'].'")';
        } else {
            $textarea = '"textarea":$("#' . $this->options['id'] . '")';
        }

        unset($options['textarea']);

        if ( !empty($options['upload']) && is_array($options['upload']) ) {
            $options['upload'] = array_merge($this->defaultUploadOptions, $options['upload']);
        } else {
            $options['upload'] = false;
        }
        
        $jsonOption = json_encode($options);
        $jsonOption = '{'. $textarea . ',' . trim($jsonOption,'{} ') . '}';
        // $jsonOption = '{'. $textarea . '}';

        return $jsonOption;
    }
}